package manager

import (
	"fmt"
	"github.com/tianjigames/fairy/dao"
	"github.com/tianjigames/fairy/model"
	"github.com/tianjigames/fairy/pojo"
	"github.com/tianjigames/fairy/template"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/logger"
	"sync"
)

var (
	RideManager *rideManager
	rideManagerOnce sync.Once
)


/**
坐骑管理器
 */
type rideManager struct {
	BaseManager
}

func NewRideManager() *rideManager {
	rideManagerOnce.Do(func() {
		RideManager = &rideManager{}
	})
	return RideManager
}

/**
初始化玩家坐骑
 */
func (p *rideManager) InitPlayerRide(player *model.PlayerObject) (bool,error) {
	rideList := player.RideList
	if rideList == nil {
		rideList = model.NewRideList()
	}

	dbList := make([]*pojo.RideData,0)
	err := dao.RideDataDao.GetListByDb(&pojo.RideData{
		PlayerGuid: player.GetGuid(),
	},&dbList)
	if err != nil {
		logger.Log.Errorf("[RideManager] InitPlayerRide failed,error:%s",err.Error())
		return false,err
	}

	rideIdx := 0
	if len(dbList) > 0 {
		for _,it := range dbList {
			v := pitaya.GetTemplateById(template.RideBaseKey,fmt.Sprintf("%d",it.TemplateId))
			if v == nil {
				continue
			}

			cfg := v.(*template.RideBase)

			ride := &model.Ride{
				MDBData: it,
				MRideBase: cfg,
			}

			if ride.CanRemove() {
				continue
			}

			ride.SetIndex(rideIdx)
			rideList.SetRideData(ride.GetIndex(),ride)
			if it.DefFlag > 0 {
				rideList.SetDefaultIndex(ride.GetIndex(),player)
			}
			rideIdx += 1

			//todo:处理特殊事件


		}
	}

	if rideList.MNRideCount > 0 && rideList.MNDefaultIndex <= -1 {
		rideList.SetDefaultIndex(0,player)
		rideList.GetRideData(0).SetDefFlag(1)
	}
	player.RideList = rideList
	return true,nil
}




















